package com.chixing.listener;

import com.chixing.config.RabbitMQConfig;
import com.chixing.entity.Orders;
import com.chixing.service.IOrdersService;
import com.chixing.utils.Result;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 监听死信队列：处理订单超时自动取消
 */

@Component
public class OrderTimeoutListener {
    @Autowired
    private IOrdersService ordersService;

    @RabbitListener(queues = RabbitMQConfig.ORDER_DEAD_QUEUE)
    @RabbitHandler
    public void handleOrderTimeout(Long orderId, Message message, Channel channel){
        try {
            System.out.println("收到超时订单：id = " + orderId);

            //查询订单状态
            Result result = ordersService.getByOrderId(orderId);
            System.out.println("死信队列收到的result.getData():" + result.getData());

            if (result.getCode() != 200){
                System.out.println("订单不存在");
                return;
            }

            //去除result中嵌套的真正的订单status
            Object data = result.getData();
            Orders order = null;
            if (data instanceof java.util.Map<?, ?> mapData) {
                Object orderObj = mapData.get("order");
                if (orderObj instanceof Orders o) {
                    order = o;
                } else {
                    System.out.println("Result.getData()中没有正确的订单对象");
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    return;
                }
            } else {
                System.out.println("返回数据类型异常: " + data.getClass());
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            if (!"待支付".equals(order.getOrderStatus())){
                System.out.println("订单状态为：" + order.getOrderStatus());
                return;
            }

            long userId = order.getUserId();

            //调用订单取消方法
            ordersService.cancelUnpaidOrder(orderId,(int)userId);
            //消息确认
            // requeue: false 不重入队列，立马删除 ； true:重入队列,不删除
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
            System.out.println("处理订单超时成功...");
        }catch (Exception e){
            System.out.println("定单超时处理失败...");
        }

    }

}
